<template>
  <view class="check-in">
    <view class="check-in-content">
      <nut-tabbar
        :bottom="true"
        @tab-switch="tabSwitch"
        unactive-color="#2C2C2C"
        active-color="#1E74FD"
      >
        <nut-tabbar-item tab-title="打卡">
          <template #icon>
            <i
              class="iconfont icon-qiandao-kaoqindaqia"
              style="font-size: 46rpx"
            ></i>
          </template>
        </nut-tabbar-item>
        <nut-tabbar-item
          tab-title="统计"
          icon="category"
        >
          <template #icon>
            <i
              class="iconfont icon-tongji"
              style="font-size: 40rpx"
            ></i>
          </template>
        </nut-tabbar-item>
        <nut-tabbar-item
          tab-title="管理"
          icon="category"
        >
          <template #icon>
            <i
              class="iconfont icon-guanlileixiangmuguanli"
              style="font-size: 46rpx"
            ></i>
          </template>
        </nut-tabbar-item>
      </nut-tabbar>
      <view class="">
        <view
          class=""
          v-if="tabsBottomSwitch == 0"
        >
          <nut-tabs
            v-model="activeTab"
            :swipeable="true"
            @change="changeTab"
          >
            <nut-tab-pane
              v-for="tab in tabs"
              :key="tab.id"
              :title="tab.title"
              :disabled="tab.disabled"
            >
              <view
                class="check-in-item"
                v-if="activeTab == 0"
              >
                <view class="con-title">
                  <view class="con-title-left">
                    <img
                      :src="userInfo?.avatarUrls"
                      alt=""
                    />
                    <view class="title-text">
                      <text>{{ userInfo?.nickName }}</text>
                      <text>{{ userInfo?.deptName }}</text>
                    </view>
                  </view>
                  <view class="con-title-right">
                    <img
                      src="https://img.alicdn.com/imgextra/i4/1034622205/O1CN01MB6V9y1S9wNwEcO0J_!!1034622205.png"
                      alt=""
                    />
                    <text>申请</text>
                  </view>
                </view>
                <!-- 定位提示 -->
                <view
                  class="positioning-prompt"
                  v-if="false"
                >
                  <view class="positioning-prompt-box">
                    <view class="positioning-prompt-left">
                      <i class="iconfont icon-tishi"></i>
                    </view>
                    <view class="positioning-prompt-right">
                      <text>你尚未授权“打卡”访问你的位置信息，无法正常使用 打卡功能</text>
                    </view>
                  </view>
                </view>
                <!-- 打卡 -->
                <template v-if="!isCheckIn">
                  <view class="con-item">
                    <view class="con-item-left">
                      <view class="check-in-time-box">
                        <view class="time">
                          <!-- active 改变状态是否打卡状态 -->
                          <view class="in-time">
                            <view class="check-icon">
                              <text></text>
                              <!--占位-->
                            </view>
                            <view class="in-time-text">
                              <text>上班时间 {{ atendanceRecordData?.startTime }}</text>
                              <nut-tag
                                v-if="false"
                                :color="attendanceStatusColor[atendanceRecordData?.attendanceStatus]?.color"
                                :text-color="attendanceStatusColor[atendanceRecordData?.attendanceStatus]?.textColor"
                                >缺卡</nut-tag
                              >
                            </view>
                          </view>
                          <!-- 外勤 -->
                          <view
                            class="check-field-personnel"
                            v-if="
                              !isCheckInBtn &&
                              atendanceRecordData?.checkInTime == null &&
                              atendanceRecordData?.checkOutTime == null
                            "
                          >
                            <text> 右滑可切换至外勤打卡 </text>
                          </view>
                          <!-- 缺卡 -->
                          <view
                            class="check-miss"
                            v-if="false"
                          >
                            <text>申请纠正<i class="iconfont icon-youjiantou1"></i></text>
                          </view>
                          <!-- 正常打卡时间 -->
                          <view
                            class="check-time"
                            v-if="true"
                          >
                            <view class="check-time-text">
                              <text
                                >打卡时间
                                {{
                                  atendanceRecordData?.checkInTime
                                    ? atendanceRecordData?.checkInTime?.substring(11, 16)
                                    : ""
                                }}</text
                              >
                              <nut-tag
                                :color="attendanceStatusColor[atendanceRecordData?.attendanceStatus]?.color"
                                :text-color="attendanceStatusColor[atendanceRecordData?.attendanceStatus]?.textColor"
                                >{{ checkStatusList[atendanceRecordData?.attendanceStatus]?.dictLabel }}</nut-tag
                              >
                            </view>
                            <view class="check-adress">
                              <i class="iconfont icon-wifi"></i>
                              <text>{{ atendanceRecordData?.wifiName }}</text>
                            </view>
                          </view>
                        </view>
                        <view class="time">
                          <!-- active 改变状态是否打卡状态 -->
                          <view class="in-time active">
                            <view class="check-icon">
                              <text></text>
                            </view>
                            <text class="in-time-text">下班时间 {{ atendanceRecordData?.endTime }}</text>
                          </view>
                          <!-- 外勤 -->
                          <view
                            class="check-field-personnel"
                            v-if="false"
                          ></view>
                          <!-- 正常打卡时间 -->
                          <view
                            class="check-time"
                            v-else
                          >
                            <view class="check-time-text">
                              <text
                                >打卡时间
                                {{
                                  atendanceRecordData?.checkOutTime
                                    ? atendanceRecordData?.checkOutTime?.substring(11, 16)
                                    : ""
                                }}</text
                              >
                              <nut-tag
                                :color="attendanceStatusColor[atendanceRecordData?.attendanceOutStatus]?.color"
                                :text-color="attendanceStatusColor[atendanceRecordData?.attendanceOutStatus]?.textColor"
                                >{{ checkStatusList[atendanceRecordData?.attendanceOutStatus]?.dictLabel }}</nut-tag
                              >
                            </view>
                            <view class="check-adress">
                              <i class="iconfont icon-wifi"></i>
                              <text>{{ atendanceRecordData?.wifiName }}</text>
                            </view>
                          </view>
                        </view>
                      </view>
                    </view>
                    <view class="con-item-right">
                      <view class="positioning-btn">
                        <i class="iconfont icon-shuaxin"></i>
                        <text>重新定位</text>
                      </view>
                    </view>
                  </view>
                  <view class="check-in-btn">
                    <!-- grey 灰色  orange 橙色 blue 蓝色-->
                    <view
                      class="check-btn-con"
                      @click="checkIn"
                      :class="{
                        grey: !isCheckInBtn,
                        blue: isCheckInBtn,
                        orange: isCheckInBtn && letAttendanceStatus == 1,
                      }"
                    >
                      <view class="check-btn">
                        <view class="check-btn-text-box">
                          <view class="check-btn-text">
                            <text v-if="letAttendanceStatus == 1">上班打卡</text>
                            <text v-else>下班打卡</text>
                          </view>
                          <view class="check-btn-time">
                            <text>{{ todayTimes }}</text>
                          </view>
                        </view>
                      </view>
                      <view class="ripple-circle ripple-circle1"></view>
                      <view class="ripple-circle ripple-circle2"></view>
                      <view class="ripple-circle ripple-circle3"></view>
                    </view>
                    <view class="check-btn-placeholder">
                      <view
                        class="placeholder-box"
                        v-if="false"
                      >
                        <i class="iconfont icon-tixingshixin"></i>
                        <text>未进入打卡范围</text>
                      </view>
                      <view
                        class="placeholder-box"
                        v-if="false"
                      >
                        <i class="iconfont icon-tixingshixin grey"></i>
                        <text>请连接公司指定WIFI进行打卡</text>
                      </view>
                      <view
                        class="placeholder-box"
                        v-if="false"
                      >
                        <i class="iconfont icon-check_bg_black blue"></i>
                        <text>未到打卡时段：视为早退</text>
                      </view>
                      <view
                        class="placeholder-box"
                        v-else
                      >
                        <i class="iconfont icon-check_bg_black blue"></i>
                        <text>已进入打卡范围：袋鼠播播_</text>
                      </view>
                    </view>
                  </view>
                </template>
                <template v-else>
                  <view class="check-in-success">
                    <view class="check-in-success-box">
                      <view class="check-success-status">
                        <img
                          src="https://img.alicdn.com/imgextra/i4/1034622205/O1CN01aDnpil1S9wO5JIFZK_!!1034622205.png"
                          alt=""
                        />
                        <text>今日打卡已完成!</text>
                        <view
                          class="update-check-in"
                          @click="updateCheckIn"
                          >更新打卡</view
                        >
                      </view>
                      <view class="check-success-list">
                        <view class="check-success-item">
                          <view class="check-success-title">
                            <text></text>
                            <text>今日打卡详情</text>
                          </view>
                          <view class="con-item">
                            <view class="con-item-left">
                              <view class="check-in-time-box">
                                <view class="time">
                                  <!-- active 改变状态是否打卡状态 -->
                                  <view class="in-time">
                                    <view class="check-icon">
                                      <text></text>
                                      <!--占位-->
                                    </view>
                                    <view class="in-time-text">
                                      <text>上班时间 {{ atendanceRecordData?.startTime }}</text>
                                      <nut-tag
                                        v-if="false"
                                        color="#EEF4FF"
                                        text-color="#1E74FD"
                                        >缺卡</nut-tag
                                      >
                                    </view>
                                  </view>
                                  <!-- 外勤 -->
                                  <view
                                    class="check-field-personnel"
                                    v-if="false"
                                  >
                                    <text> 右滑可切换至外勤打卡 </text>
                                  </view>
                                  <!-- 缺卡 -->
                                  <view
                                    class="check-miss"
                                    v-if="false"
                                  >
                                    <text>申请纠正<i class="iconfont icon-youjiantou1"></i></text>
                                  </view>
                                  <!-- 正常打卡时间 -->
                                  <view
                                    class="check-time"
                                    v-if="true"
                                  >
                                    <view class="check-time-text">
                                      <text
                                        >打卡时间
                                        {{
                                          atendanceRecordData?.checkInTime
                                            ? atendanceRecordData?.checkInTime?.substring(11, 16)
                                            : ""
                                        }}</text
                                      >
                                      <nut-tag
                                        :color="attendanceStatusColor[atendanceRecordData?.attendanceStatus]?.color"
                                        :text-color="
                                          attendanceStatusColor[atendanceRecordData?.attendanceStatus]?.textColor
                                        "
                                        >{{ checkStatusList[atendanceRecordData?.attendanceStatus]?.dictLabel }}
                                      </nut-tag>
                                    </view>
                                    <view class="check-adress">
                                      <i class="iconfont icon-wifi"></i>
                                      <text>{{ atendanceRecordData?.wifiName }}</text>
                                    </view>
                                    <!-- 请假 -->
                                    <view class="leave"></view>
                                  </view>
                                </view>
                                <view class="time">
                                  <!-- active 改变状态是否打卡状态 -->
                                  <view class="in-time active">
                                    <view class="check-icon">
                                      <text></text>
                                    </view>
                                    <text class="in-time-text">下班时间 {{ atendanceRecordData?.endTime }}</text>
                                  </view>
                                  <!-- 外勤 -->
                                  <view
                                    class="check-field-personnel"
                                    v-if="false"
                                  ></view>
                                  <!-- 正常打卡时间 -->
                                  <view
                                    class="check-time"
                                    v-else
                                  >
                                    <view class="check-time-text">
                                      <text
                                        >打卡时间
                                        {{
                                          atendanceRecordData?.checkOutTime
                                            ? atendanceRecordData?.checkOutTime?.substring(11, 16)
                                            : ""
                                        }}</text
                                      >
                                      <nut-tag
                                        :color="attendanceStatusColor[atendanceRecordData?.attendanceOutStatus]?.color"
                                        :text-color="
                                          attendanceStatusColor[atendanceRecordData?.attendanceOutStatus]?.textColor
                                        "
                                        >{{ checkStatusList[atendanceRecordData?.attendanceOutStatus]?.dictLabel }}
                                      </nut-tag>
                                    </view>
                                    <view class="check-adress">
                                      <i class="iconfont icon-dingwei1"></i>
                                      <text>{{ atendanceRecordData?.wifiName }}</text>
                                    </view>
                                  </view>
                                </view>
                              </view>
                            </view>
                          </view>
                        </view>
                      </view>
                    </view>
                  </view>
                </template>
              </view>
              <view
                class=""
                v-if="activeTab == 1"
              >
                外勤
              </view>
            </nut-tab-pane>
          </nut-tabs>
        </view>
        <view
          class=""
          v-if="tabsBottomSwitch == 1"
        >
          <Statistics />
        </view>
        <view
          class="management"
          v-if="tabsBottomSwitch == 2"
        >
          <AttendanceManage />
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import Taro, { useDidShow } from "@tarojs/taro";
import Statistics from "../statistics/index.vue";
import AttendanceManage from "../attendanceManage/index.vue";
import { postIsPunchCard, addAttendanceRecord, getAttendanceRecordQueryData, getDictDataTypeList } from "@/api/index";
import { wechatGetSetting, wechatAuthorize } from "@/libs/wechat/runtime/index";
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { times, formatDates } from "@/utils/utils";
import { getCurrentLocation } from "@/utils/wifiAuth";
import { userInfoStore } from "@/stores/userInfoStore";
const store = userInfoStore();
const isCheckIn = ref(false);
const userInfo = computed(() => Taro.getStorageSync("user"));
const tabs = ref([
  { id: 0, title: "上下班打卡", disabled: false },
  { id: 1, title: "外勤打卡", disabled: true },
]);

const tabsBottomSwitch = ref(0);
const activeTab = ref(0);
const isWifi = ref(false);
const wifiName = ref("");
const loading = ref(false);
const wifiInfo = ref<{
  ssid?: string;
  bssid?: string;
  secure?: boolean;
  signalStrength?: number;
} | null>(null);
const position = ref();
const punchCards = ref();
const errorMsg = ref("");
const deviceModel = ref(""); // 设备型号
const isWorkCard = ref(false); // 是否打上班卡
const isOffWorkCard = ref(false); // 是否打下班卡
const todayTimes = ref(); // 当天的时分秒.
const isCheckInData = ref(); // 是否能打卡的数据data
const hadClocked = ref(false); // 是否已经全部打卡
const isCheckInBtn = ref(false); // 按钮是否能显示打卡
const atendanceRecordData = ref(); // 考勤记录列表
const checkStatusList = ref([]); // 考勤状态列表
const letAttendanceStatus = ref(0); // 考勤状态计算(0.正常，1.迟到，2.早退，3.缺勤)
const attendanceStatusColor = ref([
  {
    color: "#EEF4FF",
    textColor: "#1E74FD",
  },
  {
    color: "#FFF3E3",
    textColor: "#FF8000",
  },
  {
    color: "#FEECEC",
    textColor: "#E90800",
  },
  {
    color: "#F0F0F0",
    textColor: "#666",
  },
]);
let timer: number | null = null; // 定时器
onMounted(async () => {
  await handleGetAttendanceQueryData(); // 考勤记录列表
  await handleGetWifi();
  await handleGetCurrentLocation();
  await getDeviceModel();
  getDictMeetingPurviewFun("check_status");
  // 每秒更新一次
  updateTime();
  timer = setInterval(updateTime, 1000) as unknown as number;
  await handleAttendanceStatus();
});
useDidShow(() => {
  // onLoad();
});
const handleAttendanceStatus = async () => {
  if (new Date() > new Date(`${formatDates(new Date())} 09:30:00`) && atendanceRecordData.value?.checkInTime == null) {
    letAttendanceStatus.value = 1;
    // 下班卡没打，并且当前时间小于下班打卡时间，则早退
  } else if (new Date() < new Date(`${formatDates(new Date())} 18:30:00`)) {
    letAttendanceStatus.value = 2;
    // 上班卡和下班卡都没打，并且当前时间大于上班打卡时间，则缺勤
  } else if (
    !atendanceRecordData.value?.checkInTime &&
    !atendanceRecordData.value?.checkOutTime &&
    new Date() > new Date(`${formatDates(new Date())} 18:30:00`)
  ) {
    letAttendanceStatus.value = 3;
  } else {
    letAttendanceStatus.value = 0;
  }
  console.log(letAttendanceStatus.value, "letAttendanceStatus");
};
// 字典获取（会议提醒）
const getDictMeetingPurviewFun = async dictType => {
  await getDictDataTypeList(dictType).then(res => {
    if (dictType == "check_status") {
      checkStatusList.value = res.data;
    }
  });
};
// 监听判断是否能打卡 isCheckInBtn
watch(
  () => isCheckInData.value?.flag,
  val => {
    // if (isCheckInData.value?.flag && (!punchCards.value?.checkInTime || !punchCards.value?.checkOutTime)) {
    isCheckInBtn.value = val;
    console.log(isCheckInBtn.value, "isCheckInBtn");

    // }
  },
);
// 动态获取时分秒,每秒更新一次获取最新的时间
onUnmounted(() => {
  if (timer) clearInterval(timer);
});

// 考勤记录列表
const handleGetAttendanceQueryData = async () => {
  let params = {
    userId: Taro.getStorageSync("user").userId,
    date: formatDates(new Date()),
  };
  await getAttendanceRecordQueryData(params).then(res => {
    atendanceRecordData.value = res.data;
    store.punchCards = res.data;
    isCheckIn.value = atendanceRecordData.value?.checkInTime && atendanceRecordData.value?.checkOutTime;
  });
};
//
const handlePunchCards = async () => {
  punchCards.value = JSON.parse(JSON.stringify(store.punchCards));
  isWorkCard.value =
    (!atendanceRecordData.value?.checkInTime && !atendanceRecordData.value.checkOutTime && isCheckInData.value?.flag) ??
    false; // 是否打上班卡
  isOffWorkCard.value =
    (atendanceRecordData.value?.checkInTime && !atendanceRecordData.value.checkOutTime && isCheckInData.value?.flag) ??
    false; // 是否打下班卡
};
// 点击打卡
const checkIn = () => {
  if (loading.value) return;
  if (!isCheckInData.value?.flag) {
    Taro.showToast({
      title: isCheckInData.value?.msg,
      icon: "none",
    });
    return;
  }
  // 如果上下班都打卡了，就置灰
  if (atendanceRecordData?.checkInTime && atendanceRecordData?.checkOutTime && isCheckInData.value?.flag) {
    hadClocked.value = true;
    Taro.showToast({
      title: "您已打卡",
      icon: "none",
    });
    return;
  }
  handleAddAttendanceRecord();
};
const handleAddAttendanceRecord = async () => {
  await handleAttendanceStatus();
  let params = {};
  // 上班打卡参数
  if (atendanceRecordData.value?.checkInTime == null) {
    params = {
      userId: Taro.getStorageSync("user").userId,
      attendanceDate: formatDates(new Date()),
      checkInTime: isWorkCard.value
        ? formatDates(new Date()) + " " + todayTimes.value
        : atendanceRecordData.value?.checkInTime,
      attendanceStatus: letAttendanceStatus.value,
      checkType: 1,
      type: 1,
    };
  }
  if (atendanceRecordData.value?.checkInTime != null) {
    params = {
      userId: Taro.getStorageSync("user").userId,
      attendanceDate: formatDates(new Date()),
      checkOutTime: isOffWorkCard.value
        ? formatDates(new Date()) + " " + todayTimes.value
        : atendanceRecordData.value?.checkOutTime,
      attendanceOutStatus: letAttendanceStatus.value,
      checkType: 1,
      type: isWorkCard.value ? 1 : 2,
    };
  }
  console.log(params, "params666999");
  loading.value = true;
  addAttendanceRecord(params)
    .then(async res => {
      Taro.showModal({
        title: "提示",
        content: !atendanceRecordData.value?.checkInTime ? "上班打卡成功" : "下班打卡成功",
        showCancel: false,
        success: async function (res) {
          if (res.confirm) {
            if (atendanceRecordData.value?.checkInTime != null) {
              isCheckIn.value = true;
            }
            console.log("用户点击确定");
            onLoad();

            loading.value = false;
            // 更新数据
            store?.getPunchCards();
          }
        },
      });
    })
    .catch(err => {
      loading.value = false;
    });
};
const updateTime = () => {
  todayTimes.value = times(new Date());
};
// 获取设备型号
const getDeviceModel = async () => {
  try {
    const res = Taro.getDeviceInfo();
    deviceModel.value = res.model;
  } catch (err) {
    console.error("获取设备型号失败:", err);
  }
};

// 获取位置
const handleGetCurrentLocation = async () => {
  getCurrentLocation()
    .then(async location => {
      position.value = location;
      await handlePostIsPunchCard();
      console.log(location, "获取位置成功888");
    })
    .catch(err => {
      console.error("获取位置失败2:", err);
    });
};
const handleGetWifi = async () => {
  Taro.stopWifi();
  try {
    Taro.startWifi({
      success: async function (res) {
        Taro.onWifiConnected(async res => {
          wifiInfo.value = res.wifi;
          console.log(res, "获取Wi-Fi信息成功");
        });
        Taro.getConnectedWifi();
      },
      fail: function (err) {
        console.log(err, "err6669");
      },
    });
  } catch (err) {
    errorMsg.value = "获取Wi-Fi信息失败566";
  } finally {
    loading.value = false;
  }
};

const getWechatAuthorize = async () => {
  await wechatAuthorize().then(async res => {
    console.log(res, "res1112");
  });
};

// 检查网络类型
const checkNetworkType = async () => {
  try {
    // const res = await Taro.getNetworkType();
    const res = await Taro.getNetworkType();
    isWifi.value = res.networkType === "wifi";
    console.log("当前网络类型:", res, "是否WiFi:", isWifi.value);
  } catch (err) {
    console.error("获取网络类型失败:", err);
  }
};

// 获取是否能打卡
const handlePostIsPunchCard = async () => {
  if (wifiInfo.value?.SSID == "") {
    Taro.showToast({
      title: "请打开WiFi",
      icon: "none",
    });
    return;
  }
  if (position.value?.longitude == undefined || position.value?.latitude == undefined) {
    Taro.showToast({
      title: "请打开定位",
      icon: "none",
    });
    return;
  }
  let params = {
    userId: Taro.getStorageSync("user").userId,
    wifiName: wifiInfo.value?.SSID,
    userLat: position.value?.longitude,
    userLon: position.value?.latitude,
    sn: deviceModel.value + Taro.getStorageSync("user").userId,
    checkType: activeTab.value,
  };
  await postIsPunchCard(params).then(async res => {
    isCheckInData.value = res.data; // 是否能打卡的数据data
    await handlePunchCards();
  });
};

//切换tab
const changeTab = (val: number) => {
  console.log(val);
  console.log(activeTab.value);
};
const tabSwitch = (item, index) => {
  tabsBottomSwitch.value = index;
  let title = "";
  index == 0 ? (title = "考勤打卡") : index == 1 ? (title = "考勤统计") : (title = "考勤管理");
  console.log(item.title, "item.title");
  Taro.setNavigationBarTitle({
    title: title,
  });
};
const onLoad = async () => {
  await handleGetWifi();
  await handleGetCurrentLocation();
  await getDeviceModel();
  await handlePostIsPunchCard();
  await handleAttendanceStatus(); // 考勤状态
  // await handlePunchCards();
  await handleGetAttendanceQueryData(); // 考勤记录列表
  await getWechatAuthorize();
  await checkNetworkType();
  setInterval(updateTime, 1000);
};
const updateCheckIn = () => {
  console.log("更新");
  isCheckIn.value = false;
};
// 打卡
const handlePunchCard = async () => {
  let params = {
    userId: Taro.getStorageSync("user").userId,
    wifiName: wifiInfo.value?.SSID,
    userLat: position.value?.longitude,
    userLon: position.value?.latitude,
    sn: deviceModel.value + Taro.getStorageSync("user").userId,
    checkType: activeTab.value,
  };
  postPunchCard(params).then(res => {
    if (res.code == 200) {
      Taro.showToast({
        title: "打卡成功",
        icon: "none",
      });
    }
  });
};
</script>

<style lang="less">
@import url("./index.less");
</style>
